const fs = require('fs')
const path = require('path')

//定义正则表达式，分别匹配<style></style>和<script></script>
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/

fs.readFile(path.join(__dirname,'./index.html'),'utf8',function(err,dataStr){
  if(err) return console.log('读取HTML文件失败'+err.message)
    resolveCSS(dataStr)
    resolveJS(dataStr)
    resolveHTML(dataStr)
}) 

function resolveCSS(dataStr){
  const r1 = regStyle.exec(dataStr)
  const newCSS = r1[0].replace('<style>','').replace('</style>','')
  fs.writeFile(path.join(__dirname,'./index.css'),newCSS,function(err){
    if(err) return console.log('写入CSS文件失败'+err.message)
    console.log('写入CSS文件成功')
  })
}

function resolveJS(dataStr){
  const r2 = regScript.exec(dataStr)
  const newJS = r2[0].replace('<script>','').replace('</script>','')
  fs.writeFile(path.join(__dirname,'./index.js'),newJS,function(err){
    if(err) return console.log('写入JS文件失败'+err.message)
    console.log('写入JS文件成功')
  })
}

function resolveHTML(dataStr){
  const newHTML = dataStr.replace(regStyle,'<link rel="stylesheet" href="./index.css">').replace(regScript,'<script src="./index.js"></script>')
  fs.writeFile(path.join(__dirname,'./index.html'),newHTML,function(err){
    if(err) return console.log('写入HTML文件失败'+err.message)
    console.log('写入HTML文件成功')
  })
}